package com.pug.user.handler;

import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import xq.pug.common.exception.ServiceException;
import xq.pug.common.result.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author RenGaoshuai
 * @date 2023/7/13 9:33
 * @description
 */
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 入参校验拦截
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R<?> throwCustomException(MethodArgumentNotValidException e) {
        return R.ofFail(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 自定义业务异常
     *
     * @param req
     * @param e
     * @param resp
     * @return
     */
    @ExceptionHandler(value = ServiceException.class)
    public R<?> serviceErrorHandler(HttpServletRequest req, ServiceException e, HttpServletResponse resp) {
        return R.ofFail(e.getErrCode(), e.getMesg());
    }

    @ExceptionHandler(value = Exception.class)
    public R<?> exception(HttpServletRequest req, ServiceException e, HttpServletResponse resp) {
        return R.ofFail("系统异常");
    }
}
